// xredis
package main

import (
	"color"
	"flag"
	"fmt"
	"github.com/gosexy/redis"
	"strings"
	"time"
)

func GetInfo(c *redis.Client, sec string) map[string]string {
	s, err := c.Info(sec)
	if err != nil {
		fmt.Println("get key failure")
		return nil
	}
	a1 := strings.Split(s, "\n")
	m1 := make(map[string]string)
	for i := 1; i < len(a1); i++ {
		if !strings.Contains(a1[i], ":") {
			break
		}
		a2 := strings.Split(a1[i], ":")
		m1[a2[0]] = a2[1]
	}
	return m1
}

func Help() {
	color.Cyan("Version: xredis_v1.0\n")
	fmt.Printf("Usage:./xredis -i=\"192.168.1.1\" -p=\"6379\" -w=\"password\"\n")
	fmt.Printf("Usage:./xredis\n")
	fmt.Printf("Usage:./xredis -json=true\n")
	fmt.Printf("Usage:./xredis -k=true,print key=value\n")
	fmt.Printf("defautl ip=127.0.0.1 default port=6379\n")
}

func main() {
	//fmt.Println("Hello World!")
	//T_out := time.Second * 10
	help := flag.Bool("h", false, "show help")
	ip := flag.String("i", "127.0.0.1", "redis server ip")
	port := flag.Uint("p", 6379, "redis server port")
	pass := flag.String("w", "", "redis server password")
	//timeout := flag.Duration("t", T_out, "connect redis timeout")
	flag.Parse()

	if *help {
		Help()
		return
	}

	T_out := time.Duration(time.Second * 10) //connect redis timeout

	client := redis.New()
	err := client.ConnectWithTimeout(*ip, *port, T_out)
	if *pass != "" {
		ss, _ := client.Auth(*pass)
		if ss != "OK" {
			fmt.Println(ss)
		}
	}
	if err != nil {
		fmt.Println("connect redis-server failure")
		return
	}
	m1 := GetInfo(client, "Server")
	fmt.Println(m1["redis_version"])
	client.Quit()

}
